package cn.znk.kedis.master_slave_model.autoconfigure;

import cn.znk.kedis.master_slave_model.properties.RedisMasterProperties;
import cn.znk.kedis.master_slave_model.utils.JacksonObjectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import redis.clients.jedis.JedisPoolConfig;

import javax.annotation.Resource;


/**
 * IntelliJ IDEA
 * project: kedis-spring-boot-starter
 *
 * @author shimi
 * @since 2021/11/21
 * @version 1.0.0
 */
@Configuration
@EnableConfigurationProperties({RedisMasterProperties.class})
@ConditionalOnWebApplication
public class RedisMasterAutoConfiguration {

    @Autowired
    private RedisMasterProperties masterProperties;

    @Resource
    private JedisPoolConfig jedisPoolConfig;

    //redis主连接工厂
    @Primary
    @Bean("masterRedisFactory")
    public JedisConnectionFactory masterJedisConnectionFactory() {
        JedisConnectionFactory masterFactory = new JedisConnectionFactory();
        masterFactory.setPort(Integer.parseInt(masterProperties.getPort()));
        masterFactory.setHostName(masterProperties.getHost());
        masterFactory.setPoolConfig(jedisPoolConfig);
        masterFactory.setTimeout(0);
        masterFactory.setPassword(masterProperties.getPassword());
        return masterFactory;
    }


    @Bean
    public RedisTemplate masterRedisTemplate(@Autowired @Qualifier("masterRedisFactory") JedisConnectionFactory factory) {
        RedisTemplate masterRedisTemplate = new RedisTemplate();
        masterRedisTemplate.setConnectionFactory(factory);
        JacksonObjectUtil.setCNJacksonObject(masterRedisTemplate);
        return masterRedisTemplate;
    }

}
